import React, { useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { getAuthAxios } from '../lib/authAxios.js';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';

dayjs.extend(relativeTime);

const JichaApp = () => {
  const [warningRows, setWarningRows] = useState([]);
  const myAxios = getAuthAxios();

  useEffect(() => {
    // 监听全局变量变化，当激活标签为稽查工单查询时初始化
    function onGlobalVarChange(e) {
      if (window.getMyGlobalVar('activeTabName') === '稽查工单查询') {
        initJichaQuery();
      }
    }

    window.addEventListener('MY_GLOBAL_VAR_CHANGE', onGlobalVarChange);
    return () => window.removeEventListener('MY_GLOBAL_VAR_CHANGE', onGlobalVarChange);
  }, []);

  // 初始化稽查工单查询页面处理逻辑
  const initJichaQuery = () => {
    const iframe = document.querySelector('#\\30 08da943e79b510de549c7f8611d8182f88194b2f690bcfdacbb68fc097b66d0');
    const iframeDom = iframe?.contentDocument || iframe?.contentWindow.document;
    if (!iframeDom) return;
    // 获取查询按钮并添加点击事件
    const queryBtn = iframeDom.querySelector('#app > div:nth-child(2) > div > div.card-first-box_yx > div > div.card-third-box_yx > div > div > form > div:nth-child(27) > div > div > div > button.el-button.el-button--primary.el-button--mini'); // 需要根据实际页面调整选择器
    if (queryBtn) {
      queryBtn.addEventListener('click', handleQueryClick(iframeDom));
      // 防止重复添加事件
      return () => queryBtn.removeEventListener('click', handleQueryClick(iframeDom));
    }
  };

  // 处理查询按钮点击事件
  const handleQueryClick = (iframeDom) => {
    if (!iframeDom) return;
    // 获取表格元素并观察变化
    const tableEl = iframeDom.querySelector('.el-table__body-wrapper'); 
    if (tableEl) {
      observeTableChanges(tableEl,iframeDom);
    }
  };

  // 观察表格变化
  const observeTableChanges = (tableEl,iframeDom) => {
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.addedNodes.length > 0) {
          processTableData(tableEl,iframeDom);
        }
      });
    });

    observer.observe(tableEl, {
      childList: true,
      subtree: true
    });

    // 初始处理
    processTableData(tableEl,iframeDom);
  };

  // 处理表格数据并应用高亮
  const processTableData = (tableEl,iframeDom) => {
    const rows = tableEl.querySelectorAll('tbody tr');
    const leftFixedTr = iframeDom.querySelectorAll("#app > div:nth-child(2) > div > div.card-first-box_yx > div > div:nth-child(3) > div.card-third-box_yx > div > div > div.table-box > div > div.el-table__fixed > div.el-table__fixed-body-wrapper > table > tbody > tr")
    if (!rows.length) return;

    const newWarningRows = [];
    const now = new Date();

    rows.forEach((tr,index) => {
      // 重置样式
      tr.style.backgroundColor = '';
      tr.style.transition = 'background-color 0.3s ease';

      const tds = tr.querySelectorAll('td');
      if (tds.length === 0) return;

      // 获取工单状态（需要根据实际表格列索引调整）
      const status = tds[17]?.textContent?.trim() || '';
      // 获取催办期限（需要根据实际表格列索引调整）
      const dueDateText = tds[45]?.textContent?.trim() || '';
      const dateEnd = tds[59]?.textContent?.trim()||""

      // 条件1：工单状态不在指定列表中
      const excludedStatuses = ['归档', '国网稽查审核', '省级稽查审核', '市级稽查审核','总部稽查审核'];
      const statusCondition = !excludedStatuses.includes(status);

      // 条件2：当前日期距催办期限小于等于3天
      const dueDate = dayjs(dueDateText);
      const dateCondition = dueDate.isValid() && dueDate.diff(now, 'day') <= 3 && dueDate.diff(now, 'day') >= 0;

      // 如果满足任一条件，高亮显示
      if (statusCondition || dateCondition && !dateEnd) {
        tr.style.backgroundColor = 'rgba(255, 183, 77, 0.4)'; // 橙色高亮
        tr.style.fontWeight = '500';
        leftFixedTr[index].style.backgroundColor = 'rgba(255, 183, 77, 0.4)'
        leftFixedTr[index].style.fontWeight = '500';
        // 添加提示信息
        tr.title = `高亮原因: ${statusCondition ? '状态未完成' : ''} ${statusCondition && dateCondition ? '且' : ''} ${dateCondition ? '距催办期限不足3天' : ''}`;

        newWarningRows.push({
          row: tr,
          workOrderNo: tds[2]?.textContent?.trim() || '未知工单', // 假设工单编号在第3列
          status,
          dueDate: dueDateText,
          statusCondition,
          dateCondition
        });
      }
    });

    setWarningRows(newWarningRows);
    // console.log('稽查工单高亮行数量:', newWarningRows.length);
  };

  return null;
};

// 创建挂载点并渲染组件
const mountPoint = document.createElement('div');
mountPoint.id = 'jicha-query-app';
document.body.appendChild(mountPoint);

// 确保只渲染一次
if (!document.querySelector('#jicha-query-app > div')) {
  const root = createRoot(mountPoint);
  root.render(<JichaApp />);
}

export default JichaApp;